﻿/*
 * Created by SharpDevelop.
 * User: Intel
 * Date: 12.12.2014
 * Time: 9:46
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Region.Utils;
using System.Data;
using System.Data.Linq;
using System.Linq;
namespace Invent
{
  /// <summary>
  /// Description of DeviceEdit.
  /// </summary>
  public partial class DeviceEdit : Form
  {
    DatabaseInvent m_db;
    Guid m_DeviceUID;
    bool m_new = false;
    DataRow getRow(){ return (from d in m_db.Devices.AsEnumerable() where d.Field<Guid>("DeviceUID")==m_DeviceUID select d).Single();}
    void ShowSelectors()
		{		  
		  Guid iPlaceUID = Guid.Empty;
		  var siPlace = PlaceUID.SelectedItem as ListItemValue;
		  if (siPlace != null) iPlaceUID = (Guid)siPlace.Value;		  
		  PlaceUID.Items.Clear();
		  PlaceUID.Items.Add(new ListItemValue(m_db.getPlaceName(Guid.Empty),Guid.Empty));
		  foreach(var r in from row in m_db.Places.AsEnumerable() orderby m_db.getPlaceName(row.Field<Guid>("PlaceUID")) select row)
		  {
		    Guid PUID = r.Field<Guid>("PlaceUID");
		    PlaceUID.Items.Add(new ListItemValue(m_db.getPlaceName(PUID),PUID));
		  }		  
		  PlaceUID.SelectedItem = new ListItemValue(m_db.getPlaceName(iPlaceUID),iPlaceUID);

		  Guid iEmployeeUID = Guid.Empty;
		  var siEmployee = EmployeeUID.SelectedItem as ListItemValue;
		  if (siEmployee != null) iEmployeeUID = (Guid)siEmployee.Value;		  
		  EmployeeUID.Items.Clear();
		  EmployeeUID.Items.Add(new ListItemValue(m_db.getEmployeeName(Guid.Empty),Guid.Empty));
		  foreach(var r in from row in m_db.Employee.AsEnumerable() orderby row.Field<String>("EmployeeName") select row)
		  {
		    Guid PUID = r.Field<Guid>("EmployeeUID");
		    EmployeeUID.Items.Add(new ListItemValue(m_db.getEmployeeName(PUID),PUID));
		  }		  
		  EmployeeUID.SelectedItem = new ListItemValue(m_db.getEmployeeName(iEmployeeUID),iEmployeeUID);

		  Guid iDeliveryUID = Guid.Empty;
		  var siDelivery = DeliveryUID.SelectedItem as ListItemValue;
		  if (siDelivery != null) iDeliveryUID = (Guid)siDelivery.Value;		  
		  DeliveryUID.Items.Clear();
		  DeliveryUID.Items.Add(new ListItemValue(m_db.getDeliveryName(Guid.Empty),Guid.Empty));
		  foreach(var r in from row in m_db.Delivery.AsEnumerable() orderby row.Field<String>("DeliveryName") select row)
		  {
		    Guid PUID = r.Field<Guid>("DeliveryUID");
		    DeliveryUID.Items.Add(new ListItemValue(m_db.getDeliveryName(PUID),PUID));
		  }		  
		  DeliveryUID.SelectedItem = new ListItemValue(m_db.getDeliveryName(iDeliveryUID),iDeliveryUID);

		  String iDeviceType = DeviceType.Text;
		  DeviceType.Items.Clear();
		  DeviceType.Items.Add("");
		  foreach(var r in from row in m_db.Devices.AsEnumerable() group row by row.Field<String>("DeviceType") into r1 orderby r1.Key select r1)
		    if (r.Key !="")
		  {
		    DeviceType.Items.Add(r.Key);
		  }		  
		  DeviceType.SelectedItem = iDeviceType;
		  
		  String iDeviceModel = DeviceModel.Text;
		  DeviceModel.Items.Clear();
		  DeviceModel.Items.Add("");
		  var qDeviceModel = from row in m_db.Devices.AsEnumerable() select row;
		  if (iDeviceType!="")
		    qDeviceModel = from row in qDeviceModel where row.Field<String>("DeviceType")==iDeviceType select row;
		  foreach(var r in from row in qDeviceModel group row by row.Field<String>("DeviceModel") into r1 orderby r1.Key select r1)
		    if (r.Key !="")
		  {
		    DeviceModel.Items.Add(r.Key);
		  }		  
		  DeviceModel.SelectedItem = iDeviceModel;


		  //m_db.Places
		}
    void showFoto()
    {
      listView1.Items.Clear();
      listView1.LargeImageList = new ImageList();
      listView1.LargeImageList.ColorDepth = ColorDepth.Depth24Bit;
      listView1.LargeImageList.ImageSize = new Size(200,200/4*3);
      foreach(DataRow foto in from f in m_db.Foto.AsEnumerable() where !f.IsNull("DeviceUID") && f.Field<Guid>("DeviceUID")==m_DeviceUID select f)
      {
        String key = foto.Field<Guid>("FotoUID").ToString();
        String fotoPath =  Path.Combine(m_db.Dir.FullName,foto.Field<String>("FileLink"));
        Image image1 = null;
        try
        {
          image1 = new Bitmap(fotoPath);
        }
        catch(System.ArgumentException)
        {
          image1 = new Bitmap(1,1);
        }
        listView1.LargeImageList.Images.Add(key,image1);
        var lvi = new ListViewItem(foto.Field<String>("FotoInfo"));
        lvi.ImageKey = key;
        lvi.Tag = foto.Field<Guid>("FotoUID");
        listView1.Items.Add(lvi);
      }
    }
    public DeviceEdit(DatabaseInvent db,Guid DeviceUID)
    {
      m_db = db;
			m_DeviceUID = DeviceUID;
			if (m_DeviceUID == Guid.Empty)
			{
			  DataRow row = m_db.newDevice("Инв. номер","Наименование",Guid.Empty,Guid.Empty,Guid.Empty,"","");
			  m_DeviceUID = row.Field<Guid>("DeviceUID");
			  m_new = true;
			}
      //
      // The InitializeComponent() call is required for Windows Forms designer support.
      //
      InitializeComponent();
      
      //
      // TODO: Add constructor code after the InitializeComponent() call.
      //
      ShowSelectors();
      showFoto();
      m_db.control_read(this,getRow());
      //read();
    }
    void ButtonAddPlaceClick(object sender, EventArgs e)
    {
      var siPlace = PlaceUID.SelectedItem as ListItemValue;
      if (siPlace!=null)
      {
        var iPlaceUID = (Guid)siPlace.Value;
        var form = new PlaceEdit(m_db,iPlaceUID);
        form.ShowDialog();
        ShowSelectors();
      }
    }
    void ButtonAddEmployeeClick(object sender, EventArgs e)
    {
      var siEmployee = EmployeeUID.SelectedItem as ListItemValue;
      if (siEmployee!=null)
      {
        var iEmployeeUID = (Guid)siEmployee.Value;
        var form = new EmployeeEdit(m_db,iEmployeeUID);
        form.ShowDialog();
        ShowSelectors();
      }
    }
    void ButtonAddDeliveryClick(object sender, EventArgs e)
    {
      var siDelivery = DeliveryUID.SelectedItem as ListItemValue;
      if (siDelivery!=null)
      {
        var iDeliveryUID = (Guid)siDelivery.Value;
        var form = new DeliveryEdit(m_db,iDeliveryUID);
        form.ShowDialog();
        ShowSelectors();
      }
    }
    void Button1Click(object sender, EventArgs e)
    {
      //write();
      m_new = false;
      m_db.control_write(this,getRow());
      Close();
    }
    void Button3Click(object sender, EventArgs e)
    {
      m_db.deleteDevice(m_DeviceUID);
      Close();
    }
    void Button2Click(object sender, EventArgs e)
    {
      Close();
    }
    void DeviceEditFormClosed(object sender, FormClosedEventArgs e)
    {
      if (m_new)
        m_db.deleteDevice(m_DeviceUID);// Удалить если новый не сохранили
    }
    void InventNumTextChanged(object sender, EventArgs e)
    {
  
    }
    void ListView1DragEnter(object sender, DragEventArgs e)
    {
      if (e.Data.GetDataPresent(DataFormats.FileDrop))
      {
        var fileList = (String[])e.Data.GetData(DataFormats.FileDrop);
        Boolean cf = false;
        for(Int32 i=0;i<fileList.Length;i++)
          if (m_db.checkLink(fileList[i]))
            cf = true;
        if (cf)
          e.Effect = DragDropEffects.Copy;
      }
      
    }
    void ListView1DragDrop(object sender, DragEventArgs e)
    {
      if (e.Data.GetDataPresent(DataFormats.FileDrop))
      {
        var fileList = (String[])e.Data.GetData(DataFormats.FileDrop);
        Boolean cf = false;
        for(Int32 i=0;i<fileList.Length;i++)
          if (m_db.checkLink(fileList[i]))
        {
          var f = m_db.newFoto(m_DeviceUID,Guid.Empty,fileList[i],new FileInfo(fileList[i]).Name);
          showFoto();
        }
      }  
    }
    void ListView1DoubleClick(object sender, EventArgs e)
    {
      if (listView1.SelectedItems.Count>0)
      {
        var iFotoUID = (Guid)listView1.SelectedItems[0].Tag;
        DataRow foto = (from d in m_db.Foto.AsEnumerable() where d.Field<Guid>("FotoUID")==iFotoUID select d).Single();
        String fotoPath =  Path.Combine(m_db.Dir.FullName,foto.Field<String>("FileLink"));
        var pr = new System.Diagnostics.Process();
        pr.StartInfo.FileName = fotoPath;
        pr.Start();           
      }
    }
    void ListView1KeyUp(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Delete)
      {
        m_db.deleteFoto((Guid)listView1.SelectedItems[0].Tag);
        showFoto();
      }
    }
    void ListView1AfterLabelEdit(object sender, LabelEditEventArgs e)
    {
      var iFotoUID = (Guid)listView1.Items[e.Item].Tag;
      DataRow foto = (from d in m_db.Foto.AsEnumerable() where d.Field<Guid>("FotoUID")==iFotoUID select d).Single();
      foto["FotoInfo"] = e.Label;
      
    }
  }
}
